import { AfterViewInit, Component, Input, OnChanges, OnDestroy, SimpleChanges, ViewChild } from '@angular/core';

import { CommonService } from './../../../core/services/common.service';
import { EChartsService } from './e-charts.service';

@Component({
    selector: 'op-e-chart',
    template: `<div #chart [style.height]="chartHeight"></div>`,
    providers: [EChartsService]
})
export class EChartComponent implements AfterViewInit, OnChanges, OnDestroy {
    @Input() chartHeight?: string = '300px';
    @Input() options: object;
    @ViewChild('chart', { static: false }) private container;
    private chart: any;

    constructor(private chartsService: EChartsService,
        private commonService: CommonService) { }

    ngOnChanges(changes: SimpleChanges): void {
        if (!this.commonService.isNullOrUndefined(this.chart) && !this.commonService.isNullOrUndefined(changes.options.currentValue)) {
            this.chartsService.setOptions(this.chart, changes.options.currentValue);
        }
    }

    ngAfterViewInit(): void {
        this.chart = this.chartsService.getChart(this.container.nativeElement);
        this.resize();
    }

    ngOnDestroy(): void {
        this.chartsService.disposeChart(this.chart);
    }

    resize(): void {
        this.chartsService.resize(this.chart);
    }
}